package com.ctp.thread.active;

import javax.swing.table.DefaultTableModel;

import com.ctp.bean.MarketBean;
import com.ctp.controller.manager.TraderManager;
import com.ctp.socket.util.MarketUtil;

public class MarketUpdateThread extends Thread implements Runnable {

	private DefaultTableModel tModel = null;

	private TraderManager traderManager = TraderManager.instance();

	public void setTableModel(DefaultTableModel tModel) {
		this.tModel = tModel;

		MarketBean[] markets = new MarketBean[tModel.getRowCount()];
		for (int i = 0; i < markets.length; i++) {
			markets[i] = new MarketBean();
		}

		traderManager.setMarkets(markets);
	}

	public void run() {
		int diffIndex = tModel.getRowCount() - 1;
		MarketBean[] markets = traderManager.getMarkets();

		while (true) {
			for (int i = 0; i < diffIndex; i++) {
				String contr = (String) tModel.getValueAt(i, 0);
				String[] params = MarketUtil.getMarketParams(contr);

				if (params != null) {
					markets[i].setMarketBean(params);
					for (int j = 1; j < tModel.getColumnCount(); j++) {
						tModel.setValueAt(params[j], i, j);
					}
				}
			}

			double last = markets[0].getLastPrice() - markets[1].getLastPrice();
			double bid1 = markets[0].getBidPrice1() - markets[1].getAskPrice1();
			double ask1 = markets[0].getAskPrice1() - markets[1].getBidPrice1();

			markets[diffIndex].setKeyPrice(last, bid1, ask1);

			tModel.setValueAt(last, diffIndex, 1);
			tModel.setValueAt(bid1, diffIndex, 2);
			tModel.setValueAt(ask1, diffIndex, 4);

			try {
				Thread.sleep(200);
			} catch (Exception e) {
			}
		}
	}

}
